package com.example.fms.exception;

import com.example.fms.vo.Meta;
import com.example.fms.vo.ResponseBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseBean sysException(Exception e) {
        log.error("系统异常", e);
        return ResponseBean.failed();
    }

    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public ResponseBean sysException(BusinessException e) {
        log.error("业务异常", e);
        return ResponseBean.failed(e.getCode(), e.getMsgKey(), e.getMeta());
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public ResponseBean methodArgumentNotValidException(MethodArgumentNotValidException exception) {
        BindingResult result = exception.getBindingResult();
        StringBuilder errorMsg = new StringBuilder();
        if (result.hasErrors()) {
            List<FieldError> fieldErrors = result.getFieldErrors();
            fieldErrors.forEach(error -> {
                log.error("数据检查失败: 类{" + error.getObjectName() + "},字段{" + error.getField()
                        + "},错误信息: " + error.getDefaultMessage());
                errorMsg.append(error.getDefaultMessage()).append("!");

            });
        }
        return ResponseBean.failed(400, errorMsg.toString());
    }

}
